#include "middleviewdelegate.h"
#include <cstdio>
#include "weldtoolview.h"

extern FileData fileData;

MiddleViewDelegate::MiddleViewDelegate(GlobalData *globalDateIn, GlobalData *ioDataIn,
                                       MoveOperation *moveOperationIn, RunView *runViewIn,
                                       JogView *jogViewIn, ProgramView *programViewIn,
                                       SystemStatus *ioStatusViewIn, MessageView *messageViewIn,
                                       ProgramFileView *programFileViewIn, HomeMenuView *homeMenuViewIn,
                                       BottomView *bottomViewIn, int styleIdIn, QWidget *mainWindowIn,
                                       CommunicateNormalDelegate *communicateNormalDelegateIn)
{
    globalDate=globalDateIn;
    ioData=ioDataIn;
    moveOperation=moveOperationIn;
    runView=runViewIn;
    jogView=jogViewIn;
    programView=programViewIn;
    ioStatusView=ioStatusViewIn;
    messageView=messageViewIn;
    programFileView=programFileViewIn;
    homeMenuView=homeMenuViewIn;
    bottomView=bottomViewIn;
    communicateNormalDelegate=communicateNormalDelegateIn;

    //设置初始页面
    currentViewID = MID_VIEW_JOG;//初始界面
    lastViewID = currentViewID;
    runningBackViewID = lastViewID;

    //界面刷新定时器
    timeViewChange = new QTimer;
    connect(timeViewChange,SIGNAL(timeout()),this,SLOT(timeViewChangeSlot()));
    //timeViewChange->start(40);
    timeViewChange->start(VIEW_UPDATE);//开启 中部 定时管理器

    //统计用
    timeRunViewCount = 0;
    timeMsgViewCount = 0;
    tmpMsgSize = 0;
//    timeProFileTreeCount = 0;
    registerFlag = true;
    bottomStatus = 0;

    //文件修改与否的判断
//    isSaveFlag = true;

    //是否初始获取io数据
    ioDataFlag = true;
    tmpIoUpdateFlag = 0;

    //控制器初始化情况 完成后去除膜
    initCtrlFlag = true;
    initialDisplayStyle(styleIdIn,mainWindowIn);

}

void MiddleViewDelegate::initialDisplayStyle(int styleId,QWidget *mainWindowIn)
{
    craftToolView=new QWidget(mainWindowIn);
    craftToolView->setGeometry(75,130,450,590);
    craftToolView_staked=new QStackedWidget(craftToolView);
    craftToolView_staked->setGeometry(0,0,450,590);
    weldToolView=new WeldToolView(communicateNormalDelegate,craftToolView);
    craftToolView_staked->addWidget(weldToolView);

    switch (styleId) {
    case 1:

        craftToolView->setGeometry(100,130,450,400);
        craftToolView_staked->setGeometry(0,0,450,400);
        break;
    default:
        break;
    }
}

MiddleViewDelegate::~MiddleViewDelegate()
{
    qDebug()<<"MiddleViewDelegate():timeViewChange stop";
    timeViewChange->stop();
}

void MiddleViewDelegate::hideAllView()
{
//    runView->hide();
//    jogView->hide();
//    programView->hide();
//    ioStatusView->hide();
//    messageView->hide();

//    programFileView->hide();
//    //
//    homeMenuView->hide();

    runView->close();
    jogView->close();
    programView->close();
    ioStatusView->close();
    messageView->close();

    programFileView->close();
    //
    homeMenuView->close();
    craftToolView->close();
    weldToolView->showDialog(false);
}

/******************
 * 用于更新策略的控制
 ******************/
void MiddleViewDelegate::timeViewChangeSlot()
{
    //time_t start,finish;
    //start = clock();

    //qDebug()<<"timeViewChangeSlot()";
    //窗口切换
    //当前没有打开文件
    if(fileData.currentFileName == "")
    {
        if(currentViewID == MID_VIEW_PROGRAM)
        {
            currentViewID = MID_VIEW_PROGRAM_FILE;
        }
    }

    //判断文件修改的情况,并且作出相应的提示
    if(currentViewID != MID_VIEW_PROGRAM )//多加一個判斷&& isSaveFlag  2017.04.17改
    {
        //如果上一次的页面是Pro;判断是否需要保存内容
        if(lastViewID == MID_VIEW_PROGRAM)
        {
            if(!programView->isProgramFileSaved)//未保存 and 不是刚打开
            {
//                currentViewID = MID_VIEW_PROGRAM;
//                emit saveProgramFile_signal();
//                programView->programSaveDialog->show(); //显示提示
//                bottomView->runProgramCheckDialog->hide();//隐藏运行提示
//                isSaveFlag = false;//关闭判断
            }
        }
    }
    else
    {
        //若已保存 or 页面又进入编辑页面:开启判断
        if(programView->isProgramFileSaved || currentViewID == MID_VIEW_PROGRAM)
        {
//            isSaveFlag = true;
        }
    }

    /****************************************************/
    if(currentViewID == MID_VIEW_RUN)
    {
        if(runView->isHidden())
        {
            hideAllView();

            runView->show();
        }
        if(!programView->isProgramFileSaved)
        {
            emit saveProgramFile_signal();
        }
    }
    else if(currentViewID == MID_VIEW_JOG)
    {
        if(jogView->isHidden())
        {
            hideAllView();

            jogView->show();
        }
    }
    else if(currentViewID == MID_VIEW_PROGRAM)
    {
        if(programView->isHidden())
        {
            hideAllView();

            programView->show();
        }

    }
    else if(currentViewID == MID_VIEW_IO)
    {
        if(ioStatusView->isHidden())
        {
            hideAllView();

            ioStatusView->show();
        }
    }
    else if(currentViewID == MID_VIEW_MESSAGE)
    {
        if(messageView->isHidden())
        {
            hideAllView();

            messageView->show();
        }
    }
    else if(currentViewID == MID_HOME_MENU)
    {
        if(homeMenuView->isHidden())
        {
            hideAllView();

            homeMenuView->show();
        }
    }
    else if(currentViewID == MID_VIEW_PROGRAM_FILE)
    {
        if(programFileView->isHidden())
        {
            hideAllView();

            programFileView->newfileView->hide();
            programFileView->settingProperty->hide();
            programFileView->showThisDialog();
        }
    }
    else if(currentViewID == MID_VIEW_CRAFT_TOOL)
    {
        if(craftToolView->isHidden())
        {
            hideAllView();

            craftToolView->show();
            weldToolView->showDialog(true);
        }
    }
    else
    {}

    if(globalDate)                                          //指针已存在
    {
        //数据更新
        //qDebug()<<"login status"<<globalDate->globalLoginStatus;
//        if(globalDate->tryLock())
//        {
            //qDebug()<<"login status"<<globalDate->globalLoginStatus;
            if(globalDate->globalLoginStatus)                   //登陆后才发送信号
            {
                //判断控制器是否初始化完成
                if(EM_UPDATE_STATUS_LV1 == globalDate->initCtrlState || EM_UPDATE_STATUS_LV1 >= globalDate->initHmiState )
                {
                    emit useFilmSignal();
                    initCtrlFlag = true;
                }
                if(initCtrlFlag)
                {
                    if(EM_UPDATE_STATUS_LV2 == globalDate->initCtrlState && EM_UPDATE_STATUS_LV2 == globalDate->initHmiState)
                    {
//                        qDebug()<<"mid : close : box!";
                        emit unUseFileSianal();
                        //emit closeMsgBoxSignal();
                        initCtrlFlag = false;
                    }
                    else if(EM_UPDATE_STATUS_FAIL == globalDate->initCtrlState)
                    {
                        emit msgBoxSignal(EM_MSG_BOX_NO_BTN,tr("警告"),tr("控制器初始化失败\n请重启"));
                    }
                }

                if(EM_CONNECT_SUCCESS != globalDate->controllerIsConnected)
                {
                    //断线判断
                    moveOperation->warmStopMove();//清除移动过程中出现的断线,但依然在喂狗
                }

                //注册正常(如果机器运行时候过期?如何处理)
                if(globalDate->globalRegStatus > ENUM_TIME_GOING_PASSED)
                {
//                    globalDate->unlock();//前必须要有 解锁

                    currentViewID = MID_HOME_MENU;
                    emit changeLeftView(currentViewID);
                    if(homeMenuView->registrationDialog->isHidden())
                    {
                        hideAllView();
                        homeMenuView->show();
                        emit showRegisterDialogSignal();
                    }
                    return;
                }
                if(registerFlag)
                {
                    if(globalDate->globalRegStatus == ENUM_TIME_GOING_PASSED)
                    {
//                        globalDate->unlock();//前必须要有 解锁

                        currentViewID = MID_HOME_MENU;
                        emit changeLeftView(currentViewID);
                        if(homeMenuView->registrationDialog->isHidden())
                        {
                            hideAllView();
                            homeMenuView->show();
                            emit showRegisterDialogSignal();
                        }

                        emit msgBoxSignal(EM_MSG_BOX_SURE_BTN,tr("警告"),tr("注册有效时间剩余不足一周\n请及时注册!"));
                        registerFlag = false;

                        return;
                    }
                }

                //判断添加
                //若有消息进入,必须显示消息界面 一次
                std::vector<Message> messageVectorOut;
                globalDate->getMessageVector(messageVectorOut);
                if(messageVectorOut.size()>0 )
                {
                    if(tmpMsgSize != messageVectorOut.size())
                    {
                        tmpMsgSize = messageVectorOut.size();
                        timeMsgViewCount = 0;//大小变化 重新检查
                    }

                    if(0 == timeMsgViewCount)
                    {
                        for(int i = 0;i<messageVectorOut.size();i++)
                        {
                            if(messageVectorOut[i].MessageLevel == EM_MESSAGE_LEVEL_ERROR)
                            {
                                ////jogView->msgWarn();//存在寸动后突然报警;导致控制器依然再喂狗;现在补充解决;2017.03.23
                                //2017.04.20 新方法 直接调用(寸动 点移动 都会存在报警)
                                if(EM_CONTROL_MODE_T2>=globalDate->globalHandState)
                                {
                                    qDebug()<<"复位手动";
                                    moveOperation->warmStopMove();
                                }


                                //timeMsgViewCount = 1;//赋予标志:表示,已经进入过一次消息界面(不用再次进入)
                                currentViewID = MID_VIEW_MESSAGE;
                                emit changeLeftView(currentViewID);

                                timeMsgErrorSound();//发出声音
                                break;
                            }
                        }
                        //赋予标志:表示,已经进入过一次消息界面(不用再次进入)
                        //或者是 已经检查过一次,并没有发现error消息
                        timeMsgViewCount = 1;
                    }
                    else if(1 == timeMsgViewCount)
                    {
                        //已曾进入过消息界面提示用户
                        //已检查过
                    }
                }
                else
                {
                    timeMsgViewCount = 0;//标志清零
                }

                //若运行状态途中,IO界面等不能进入?
                //qDebug()<<globalDate->globalCurrentState;
                bottomStatus = globalDate->globalCurrentState;

                //记录返回切换
                if(currentViewID != MID_VIEW_PROGRAM && currentViewID != MID_VIEW_PROGRAM_FILE && runningBackViewID != currentViewID)//&& currentViewID != MID_HOME_MENU
                {
                    runningBackViewID = currentViewID;
                }
                //运行模式自动 而且 运行中or暂停中 不可进入编辑
                if( globalDate->globalCurrentState == ENUM_COMMAND_RUN
                            || globalDate->globalCurrentState == ENUM_COMMAND_CEASE)
                {
                    if(currentViewID == MID_VIEW_PROGRAM || currentViewID == MID_VIEW_PROGRAM_FILE)//|| currentViewID == MID_HOME_MENU
                    {
                        currentViewID = runningBackViewID;
//                        globalDate->unlock();

                        emit changeLeftView(currentViewID);

                        emit msgBoxSignal(EM_MSG_BOX_SURE_BTN,tr("警告"),tr("当前程序非停止状态\n不可进入编辑界面!"));
                        return;  //ruturn前必须要有 解锁
                    }
                }

//                globalDate->unlock();


                if(ioData)
                {
                    if(currentViewID == MID_VIEW_IO)//currentViewID == MID_VIEW_RUN ||  || currentViewID == MID_VIEW_PROGRAM
                    {
                        if(ioDataFlag)
                        {
                            //初次进入,保证数据第一次进入时候 能够第一时间快速获取
//                            ioData->lock();
                            ioData->ioUpdateFlag = E_UPDATA_TYPE_IO;
                            ioDataFlag = false;
//                            ioData->unlock();
                        }
                    }
                    else
                    {
                        if(!ioDataFlag)
                        {
                            //qDebug()<<"set io flag 0";
//                            ioData->lock();
                            ioData->ioUpdateFlag = E_UPDATA_TYPE_NONE;
                            ioDataFlag = true;
//                            ioData->unlock();
                        }
                    }
                }

                //解锁完毕,下面是当前页面的数据更新
                emit updateBottomStatus(bottomStatus);//底部更新

                if(currentViewID == MID_VIEW_RUN)
                {
                    emit updateRunningView();
                }
                else if(currentViewID == MID_VIEW_JOG)
                {
                    emit updateJogView();
                }
                else if(currentViewID == MID_VIEW_PROGRAM)
                {
                    //2017.04.18 该部分的跟新转移到 hmicomm中,在lv1结束的之后,归类为系统初始的那个函数中
//                    if(timeProFileTreeCount < 10)
//                    {
//                        if(9 == timeProFileTreeCount)//10 * 40ms 400ms(2次)
//                        {
//                            emit updateProView();//是否需要? 只需要更新第一次
//                        }
//                        timeProFileTreeCount++;
//                    }
                }
                else if(currentViewID == MID_VIEW_IO)
                {
                    // 更新IO界面
                    emit updateIoView();
                }
                else if(currentViewID == MID_VIEW_MESSAGE)
                {
                    emit updateMsgView();
                }
                else if(currentViewID == MID_HOME_MENU)
                {
                }
                else if(currentViewID == MID_VIEW_PROGRAM_FILE)
                {
                    //2017.04.18 该部分的跟新转移到 hmicomm中,在lv1结束的之后,归类为系统初始的那个函数中
//                    if(timeProFileTreeCount < 10)
//                    {
//                        if(9 == timeProFileTreeCount)//10 * 40ms 400ms(2次)
//                        {
//                            emit updateProView();//是否需要? 只需要更新第一次
//                        }
//                        timeProFileTreeCount++;
//                    }
                }
                else
                {}
            }
//            else
//            {
//                globalDate->unlock();
//            }
//        }

    }

    //finish = clock();
    //qDebug()<< "clock :"<<CLOCKS_PER_SEC;//1000000
    //qDebug()<< "time  :"<< QString::number( (double)((finish - start) / CLOCKS_PER_SEC) ,'d', 3);
    //qDebug()<< "time  :"<< QString::number( (double)((finish - start) / 1000) ,'d', 3);
}

void MiddleViewDelegate::setViewIDSlot(int id)
{
    //qDebug()<<id;
    lastViewID = currentViewID;       //保存 旧状态
    currentViewID = (EM_MID_VIEW_ID)id;                     //新状态
}

void MiddleViewDelegate::setViewIDFromReturnBtnSlot()
{
    //若当前为菜单页面
    if(currentViewID == MID_HOME_MENU)
    {
        currentViewID = lastViewID;
        return;
    }

    //若当前为程序编辑界面
    if(currentViewID == MID_VIEW_PROGRAM)
    {
//        if(globalDate->tryLock(TRYLOCKTIME))
//        {
            if(globalDate->globalCurrentState == ENUM_COMMAND_RUN || globalDate->globalCurrentState == ENUM_COMMAND_CEASE)
            {
//                globalDate->unlock();

                currentViewID = MID_VIEW_PROGRAM;
                emit msgBoxSignal(EM_MSG_BOX_SURE_BTN,tr("警告"),tr("当前程序正处于运行状态\n请点击停止按钮后再进入文件操作界面!"));
                return;  //ruturn前必须要有 解锁
            }

//            globalDate->unlock();
            currentViewID = MID_VIEW_PROGRAM_FILE;
            return;
//        }
    }
    if(currentViewID == MID_VIEW_PROGRAM_FILE)
    {
        currentViewID = MID_VIEW_PROGRAM;
        return;
    }
}

//void MiddleViewDelegate::clearTimeProFileTreeCountSLot()
//{
//    timeProFileTreeCount = 0;
//}

void MiddleViewDelegate::timeMsgErrorSound()
{
    #ifdef BUILD_ARM
//    system("/bin/app_pwm");
    emit setBuzzerPlay_signal();
    #endif
}

void MiddleViewDelegate::changeLanguageSlot(int language)
{
    if(1 == language)
    {
        translator.load("/agvwork/AgvHmi/baseBag/hmiProject/language/middleViewDelEnglishLan.qm");
        qApp->installTranslator(&translator);
    }
    else
    {
        qApp->removeTranslator(&translator);
    }
}

//void MiddleViewDelegate::getLogFileSlot(bool result, const QString &message)
//{
//    if(result)
//    {
//        ftpManage->getDirectoryFlag = false;
//        QString logFileXml = XML_LOG_FILE;
//        ftpManage->ftpGetFile(logFileXml.right(12), D_LOGFILE_PATH, D_LOGFILE_PATH);
//    }
//}
